import {
  isArray
} from "lodash";
import {
  fetch_comments_by_case_id,
  fetch_attachments_by_case_id,
  fetch_case_by_id,
  fetch_tasks_by_case_id
} from "../api/api.js";

const state = {
  current_case: {
    title: "新案件",
    desc: "",
    src: "https://img-cdn-aliyun.dcloud.net.cn/stream/icon/__UNI__HelloUniApp.png",
    tag_list: [],
    tasks: [],
    attachments: [],
    comments: [],
  },
  isDirty: false,
  current_time:"20220222"
};

const getters = {
  // 评论
  top_comments: (state, getters, rootState) => {
    return state.current_case.comments.filter(r => !r.comment_id);
  },

  // 回复
  replies: (state, getters, rootState) => {
    return state.current_case.comments.filter(r => r.comment_id)
  },

  // 任务
  tasks: (state, getters, rootState) => {
    return state.current_case.tasks;
  }


};

// actions处理异步
const actions = {
  // 加载案件详情数据
  fetch_case_by_id({ dispatch, commit }, { payload }) {
    fetch_case_by_id(payload.case_id).then((res) => {
      commit("setCase", res);
      let case_id = res._id["$oid"];
      if (case_id) {

        // 任务主要信息加载完成，现在加载附加内容
        // 加载附件
        dispatch("fetch_attachments", {
          payload: {
            case_id: case_id
          }
        });
        // 加载评论
        dispatch("fetch_comments", {
          payload: {
            case_id: case_id
          }
        });
        // 加载任务
        dispatch("fetch_tasks", {
          payload: {
            case_id: case_id
          }
        })
      }
    });
  },

  // 获取案件的评论列表
  fetch_comments({ commit }, { payload }) {
    fetch_comments_by_case_id(payload.case_id).then((res) => {
      commit("setComments", res);
    });
  },

  // 获取案件附件列表
  fetch_attachments({ commit }, { payload }) {
    fetch_attachments_by_case_id(payload.case_id).then(res => {
      commit("setAttachments", res)
    })
  },

  // 获取案件任务列表
  fetch_tasks({ commit }, { payload }) {
    fetch_tasks_by_case_id(payload.case_id).then(res => {
      commit("setTasks", res)
    })
  }
};

// mutation 必须同步，任何异步只能出现在 action 里
const mutations = {
  setCase(state, payload) {
    state.current_case = {
      ...state.current_case,
      ...payload
    }
  },
  setComments(state, payload) {
    state.current_case = {
      ...state.current_case,
      comments: payload
    }
  },
  setAttachments(state, payload) {
    if (isArray(payload) && payload.length > 0) {
      state.current_case = {
        ...state.current_case,
        attachments: [...state.current_case.attachments, ...payload]
      }
    } else {
      state.current_case = {
        ...state.current_case,
        attachments: []
      }
    }
  },
  setTasks(state, payload) {
    state.current_case = {
      ...state.current_case,
      tasks: payload
    }
  },
  addAttachments(state, payload) {
    state.current_case = {
      ...state.current_case,
      attachments: [...state.current_case.attachments, payload]
    }
  }
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
